import {
    Box,
    Button,
    Dialog,
    DialogActions,
    DialogContent,
    DialogTitle,
    Typography
} from '@mui/material';
import { useRouter } from 'next/router';
import create from 'zustand';

import Routes, { ALLOW_RETURN_URL } from '../../../../constants/routes';
import { RETURN_URL } from '../../../../constants/storage-key';
import Router from '../../../../libs/router';
import { useStyles } from '../UIs/styled-mui-dialog';

type AuthenticationExpiredStore = {
    open: boolean;
    close: () => void;
};

const useAuthenticationExpiredStore = create<AuthenticationExpiredStore>((set) => ({
    open: false,
    close: () => set({ open: false })
}));

export const authenticationExpiredDialog = () => {
    useAuthenticationExpiredStore.setState({
        open: true
    });
};

const AuthenticationExpiredDialog = () => {
    const style = useStyles();
    const { close, open } = useAuthenticationExpiredStore();
    const router = useRouter();

    const handleClickOkBtn = async () => {
        if (ALLOW_RETURN_URL.find((url) => Router.getCurrent().startsWith(url))) {
            localStorage.setItem(RETURN_URL, Router.getCurrent());
        }
        close();
        await router.push(Routes.OTP);
    };

    return (
        <Dialog open={open} maxWidth="sm" fullWidth>
            <Box className={`${style.dialogBackground} ${style.center}`}>
                <DialogTitle>
                    <Typography variant="h4" align="center" sx={{ mt: 2 }}>
                        Authentication is expired
                    </Typography>
                </DialogTitle>
            </Box>
            <DialogContent className={`${style.dialogBackground} ${style.center}`}>
                <Typography variant="h5" align="center" sx={{ width: 400, fontWeight: 'normal' }}>
                    Your session has expired. You will be ask to enter a new OTP
                </Typography>
            </DialogContent>
            <DialogActions
                className={`${style.dialogBackground} ${style.center}`}
                sx={{ px: 4, py: 2 }}
            >
                <Button
                    color="secondary"
                    variant="contained"
                    onClick={handleClickOkBtn}
                    sx={{ width: 100, mb: 2 }}
                >
                    Ok
                </Button>
            </DialogActions>
        </Dialog>
    );
};

export default AuthenticationExpiredDialog;
